#include "local_resource.h"

WinLocalResourceImpl::WinLocalResourceImpl()
{
    Gdiplus::GdiplusStartup( &m_pGdiToken, &m_gdiplusStartupInput, NULL );
    Initialize();
}

WinLocalResourceImpl::~WinLocalResourceImpl()
{
    Gdiplus::GdiplusShutdown( m_pGdiToken );
}

void WinLocalResourceImpl::Initialize()
{
    CString strPath;
    GetModuleFileName( NULL, strPath.GetBufferSetLength( MAX_PATH + 1 ), MAX_PATH );
    strPath.ReleaseBuffer();
    int nPos = strPath.ReverseFind('\\');
    if( nPos != -1 )
    {
        strPath = strPath.Left( nPos );
    }

    m_strWorkspace = strPath;
    m_strWorkspace.Append( _T("\\res\\") );
}

BOOL WinLocalResourceImpl::GetBinaryResource( LPCTSTR lpszFile, BYTE ** pBuffer, DWORD *dwSize, BOOL bCache )
{
    if( !lpszFile || !pBuffer )
    {
        return FALSE;
    }

    CString strFile = m_strWorkspace + lpszFile;
    *pBuffer = 0;
    if( dwSize )
        *dwSize = 0;

    __int64 i64Size = 0;
    DWORD   dwReadSize = 0;
    if( WinFile::GetFileSize( strFile, &i64Size ) && i64Size > 0 )
    {
        *pBuffer = new BYTE[ (unsigned)i64Size ];
        if( *pBuffer )
        {
            memset( *pBuffer, 0, (size_t)i64Size );
            dwReadSize = (DWORD)i64Size;
        }
        else
            return FALSE;

        if( !WinFile::ReadFile( strFile, *pBuffer, dwReadSize ) )
        {
            delete[] *pBuffer;
            *pBuffer = 0;
            return FALSE;
        }
        else
        {
            if( dwSize )
                *dwSize = dwReadSize;

            return TRUE;
        }
    }

    return FALSE;
}

BOOL WinLocalResourceImpl::GetImage( LPCTSTR lpszFile, WinImage & winImage, BOOL bCache )
{
    if( !lpszFile || !*lpszFile )
    {
        return FALSE;
    }

    if( bCache )
    {
        _imgcache::iterator iter = m_mapCache.find( lpszFile );
        if( iter != m_mapCache.end() )
        {
            winImage.Copy( *(iter->second) );
            return TRUE;
        }
    }

    CString strPath = m_strWorkspace + lpszFile;

    Gdiplus::Image * pImage = NULL;
    if( !ImageHelper::LoadImageFromFile( strPath, &pImage ) ||
        !pImage )
    {
        return FALSE;
    }

    BOOL bCreate = winImage.CreateFromImage( pImage );
    delete pImage;

    if( bCreate )
    {
        WinImage *pWinImage = new WinImage;
        if( pWinImage )
        {
            pWinImage->Copy( winImage );
            m_mapCache[ lpszFile ] = pWinImage;
        }

        return TRUE;
    }

    return FALSE;
}